package com.bw.live

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.SurfaceView
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ThreadUtils
import com.bw.lib_mvi.BaseActivity
import com.bw.live.common.ConstLive
import com.bw.live.databinding.ActivityLiveBinding
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas


@Route(path = ConstLive.LIVE_PATH)
class LiveActivity : BaseActivity() {
    private lateinit var binding: ActivityLiveBinding

    // 填写声网控制台中获取的 App ID
    private val appId = "d0446b0ec3d14e8496fbd37f97850256"

    // 填写频道名
    private val channelName = "channelSun"

    // 填写声网控制台中生成的临时 Token
    private val token =
        "007eJxTYOgUXH5skpYNc8y+w0vF62RZOH9P+BMpPn3LcS6VUh7VqL0KDCkGJiZmSQapycYphiapFiaWZmlJKcbmaZbmFqYGRqZmKzOupjUEMjLEhlxmYmSAQBCfiyE5IzEvLzUnuDSPgQEARlofeQ=="

    private var isBroCast: Boolean = true

    override fun getRootLayout(): View {
        binding = ActivityLiveBinding.inflate(layoutInflater)
        return binding.root
    }


    private var mRtcEngine: RtcEngine? = null

    private val mRtcEventHandler: IRtcEngineEventHandler = object : IRtcEngineEventHandler() {
        // 成功加入频道回调
        override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
            super.onJoinChannelSuccess(channel, uid, elapsed)
            ThreadUtils.runOnUiThread {
                Toast.makeText(this@LiveActivity, "Join channel success", Toast.LENGTH_SHORT)
                    .show()
            }
        }

        // 远端用户或主播加入当前频道回调
        override fun onUserJoined(uid: Int, elapsed: Int) {
            ThreadUtils.runOnUiThread {
                // 当远端用户加入频道后，显示指定 uid 的远端视频流
                setupRemoteVideo(uid)
            }
        }

        // 远端用户或主播离开当前频道回调
        override fun onUserOffline(uid: Int, reason: Int) {
            super.onUserOffline(uid, reason)
            ThreadUtils.runOnUiThread {
                Toast.makeText(this@LiveActivity, "User offline: $uid", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    }

    private fun initializeAndJoinChannel() {
        try {
            // 创建 RtcEngineConfig 对象，并进行配置
            val config: RtcEngineConfig = RtcEngineConfig()
            config.mContext = getBaseContext()
            config.mAppId = appId
            config.mEventHandler = mRtcEventHandler

// 创建并初始化 RtcEngine
            mRtcEngine = RtcEngine.create(config)
        } catch (e: Exception) {
            throw RuntimeException("Check the error")
        }

        // 启用视频模块
        mRtcEngine?.enableVideo()


// 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象
        val container = findViewById<FrameLayout>(R.id.local_video_view_container)
        val surfaceView = SurfaceView(getBaseContext())
        container.addView(surfaceView)

// 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
        mRtcEngine?.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))


// 开启本地预览
        mRtcEngine?.startPreview()

        // 创建 ChannelMediaOptions 对象，并进行配置
        val options: ChannelMediaOptions = ChannelMediaOptions()
        // 设置用户角色为 BROADCASTER (主播) 或 AUDIENCE (观众)
        if (isBroCast) {
            options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER
        } else {
            options.clientRoleType = Constants.CLIENT_ROLE_AUDIENCE
        }

// 设置频道场景为 BROADCASTING (直播场景)
        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING

// 发布麦克风采集的音频
        options.publishMicrophoneTrack = true

// 发布摄像头采集的视频
        options.publishCameraTrack = true

// 自动订阅所有音频流
        options.autoSubscribeAudio = true

// 自动订阅所有视频流
        options.autoSubscribeVideo = true


// 使用临时 Token 和频道名加入频道，uid 为 0 表示引擎内部随机生成用户名
// 成功后会触发 onJoinChannelSuccess 回调
        mRtcEngine?.joinChannel(token, channelName, 0, options)
    }


    private fun setupRemoteVideo(uid: Int) {
        val container: FrameLayout = findViewById(R.id.remote_video_view_container)
        val surfaceView = SurfaceView(getBaseContext())
        surfaceView.setZOrderMediaOverlay(true)
        container.addView(surfaceView)
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置远端视图
        mRtcEngine?.setupRemoteVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid))
    }

    private val PERMISSION_REQ_ID = 22

    // 获取体验实时音视频互动所需的录音、摄像头等权限
    private fun getRequiredPermissions(): Array<String> {
        // 判断 targetSDKVersion 31 及以上时所需的权限
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,  // 录音权限
                Manifest.permission.CAMERA,  // 摄像头权限
                Manifest.permission.READ_PHONE_STATE,  // 读取电话状态权限
                Manifest.permission.BLUETOOTH_CONNECT // 蓝牙连接权限
            )
        } else {
            arrayOf<String>(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
            )
        }
    }

    private fun checkPermissions(): Boolean {
        for (permission in getRequiredPermissions()) {
            val permissionCheck = ContextCompat.checkSelfPermission(this, permission)
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_live )
        // 如果已经授权，则初始化 RtcEngine 并加入频道
        if (checkPermissions()) {
            initializeAndJoinChannel()
        } else {
            ActivityCompat.requestPermissions(this, getRequiredPermissions(), PERMISSION_REQ_ID)
        }
    }

    // 系统权限申请回调
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (checkPermissions()) {
            initializeAndJoinChannel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mRtcEngine != null) {
            // 停止本地视频预览
            mRtcEngine?.stopPreview()
            // 离开频道
            mRtcEngine?.leaveChannel()
            mRtcEngine = null
            // 销毁引擎
            RtcEngine.destroy()
        }
    }

}

